package com.itlong.cloud.iot.alibaba.mns.polling;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;
import com.itlong.cloud.POJO.DTO.property.IotCloudElevatorStateDTO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.iot.alibaba.util.AliClient;
import com.itlong.cloud.iot.alibaba.mns.CloudQueueMessageReceiver;
import com.itlong.cloud.commons.service.IDeviceElevatorInfoService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <desc>
 *      Iot云电梯实时获取设备状态轮询类
 * </desc>
 *
 * @createDate 2018/04/10
 */
@Service
@RefreshScope
public class IotCloudElevatorDeviceStatePolling {
    private static final Logger LOG = LoggerFactory.getLogger(IotCloudElevatorDeviceStatePolling.class);
    protected static MNSClient sMNSClient;
    @Autowired
    RedisService redisService;
    @Autowired
    MessageSender messageSender;
    @Autowired
    AliClient aliClient;
    @Value("${" + PlatformConstants.MNSEndpoint + "}")
    private  String endpoint;    //消息服务Endpoint
    @Value("${" + PlatformConstants.CLOUD_ELEVATOR_DEVICE_STATE_QUEUE + "}")
    private  String QueueName;  //队列名
    private ExecutorService cachedThreadPool ; //线程池

    @Autowired
    IDeviceElevatorInfoService iDeviceElevatorInfoService;

    /**
     * <desc>
     *      线程开始轮询
     * </desc>
     *
     * @param workerId
     * @author Jiaqi.X
     * @createDate 2018/04/10
     */
    public void worker(int workerId) {
        CloudQueueMessageReceiver receiver = new CloudQueueMessageReceiver(workerId, sMNSClient, QueueName);
        while (true) {
            Message message = receiver.receiveMessage();
            //读取到设备上传的状态数据，并设置缓存
            try {
                //LOG.error(String.format("【获取云设备状态】messageId:%s,content:%s,",message.getMessageId(),message.getMessageBodyAsBase64()));
                IotCloudElevatorStateDTO dto = JsonUtil.toObject(message.getMessageBodyAsBase64(), IotCloudElevatorStateDTO.class);
                //打印日志
                LOG.info("【消费MNS里面的消息】{} {}", JSONObject.toJSONString(dto), message.getMessageBodyAsBase64());
                if(StringUtils.isNotBlank(dto.getFloor()) && !dto.getFloor().equals("-")) {
                    dto.setOverdue(DateUtil.addCurrentTime(new Date(), 120000).getTime());
                    //判断电梯状态是否是开门状态或开门到位状态，如果为是，需处理用户云电梯操作记录表当前处于预约状态的用户行程，并满足一定条件后将行程改为预约完成
                    if ((StringUtils.isNotBlank(dto.getFrontDoor()) && (!dto.getFrontDoor().equals("-1")))
                            || (StringUtils.isNotBlank(dto.getBackDoor()) && (!dto.getBackDoor().equals("-1")))) {
                        dto.setOpen(1);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("data", JsonUtil.toJSON(dto));
                        messageSender.send(RabbitMQConstant.RABBITMQ_CALL_ELEVATOR_OPERATE_STATUS_QUEUE,
                                jsonObject.toJSONString(), RabbitMQConstant.RABBITMQ_EQUIP_EXCHANGE,
                                RabbitMQConstant.RABBITMQ_CALL_ELEVATOR_OPERATE_STATUS_KEY);
                    }
                    LOG.info("===轮询阿里iot获取设备实时状态存入redis中的值============》{}",dto.toString());
                    //设置缓存
                    redisService.set(RedisConstant.REDIS_IOT_CLOUD_ELEVATOR_STATE_CACHE + dto.getDeviceName() + "_" +
                                    (StringUtils.isNotBlank(dto.getTimestamp()) ? dto.getTimestamp() : message.getFirstDequeueTime().getTime()),
                            RedisConstant.REDIS_IOT_CLOUD_ELEVATOR_STATE_CACHE_TIME, dto);
                }
            } catch (Exception e) {
                LOG.error("【MNS获取云电梯设备数据异常】" + e.getMessage());
            } finally {
                //处理完后删除队列消息
                sMNSClient.getQueueRef(QueueName).deleteMessage(message.getReceiptHandle());
            }
        }
    }

    /**
     * <desc>
     *      初始化
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2018/04/10
     */
    @PostConstruct
    public void polling(){
        //初始化线程池
        LOG.error(String.format("【获取云设备状态线程初始化】"));
        cachedThreadPool = Executors.newFixedThreadPool(10);
        CloudAccount account = aliClient.getCloudAccount(endpoint);
        sMNSClient = account.getMNSClient();
        //开启10个线程读取消息
        for(int i=1;i<=10;i++){
            int id=i;
            cachedThreadPool.execute(() -> {
                worker(id);
            });
        }
    }
}
